#pragma once
#include "oatpp/parser/json/mapping/ObjectMapper.hpp"
#include "oatpp/web/server/api/ApiController.hpp"
#include "oatpp/web/mime/multipart/Multipart.hpp"
#include "oatpp/core/macro/codegen.hpp"
#include "../vo/LoginVo.h"
#include "../vo/SetPwdVo.h"
#include "../dto/TokenDto.h"
#include "../dto/SimpleDto.h"
#include "../util/TextUtil.h"
#include "../service/ConfigService.h"
#include "../config/SystemConfig.h"

#include OATPP_CODEGEN_BEGIN(ApiController)

/**
 * 用户管理控制器
 */
class UserController : public oatpp::web::server::api::ApiController {
public:
	UserController(const std::shared_ptr<ObjectMapper>& objectMapper)
		: oatpp::web::server::api::ApiController(objectMapper)
	{}

	/**
	 * 用户登录
	 */
	//ADD_CORS(userLogin, "*", "GET,POST,PUT,DELETE,PATCH,OPTIONS", "*", "1728000")
	ENDPOINT("POST", "/user/login", userLogin,
		BODY_DTO(Object<LoginVo>, vo)) {
		// 获取登录参数
		auto username = vo->username;
		auto password = vo->password;

		// 令牌信息
		auto token = TokenDto::createShared();

		// 查找用户信息
		if (username.getValue("") != SystemConfig::get_mutable_instance().GetBoxConf().GetUser().GetUsername() || 
			password.getValue("") != SystemConfig::get_mutable_instance().GetBoxConf().GetUser().GetPassword())
		{
			token->error = -1;
			token->description = "账号或密码错误!";
			return createDtoResponse(Status::CODE_200, token);
		}

		// 返回登录结果
		token->error = 0;
		token->description = "success";
		token->value = SystemConfig::get_mutable_instance().GetBoxConf().GetUser().GetToken();
		return createDtoResponse(Status::CODE_200, token);
	}

	/**
	 * 更新密码
	 */
	ADD_CORS(setUserPwd)
	ENDPOINT("PUT", "/user/setPwd", setUserPwd,
		HEADER(String, authorization, "Authorization"),
		BODY_DTO(Object<SetPwdVo>, vo)) {

		// 返回操作结果
		auto result = SimpleDto::createShared();
		result->error = -1;
		result->description = "服务器内部错误!";

		// 查找用户信息
		if (SystemConfig::get_mutable_instance().GetBoxConf().GetUser().GetToken() != 
			TextUtil::get_mutable_instance().GetToken(authorization.getValue("")))
		{
			result->description = "无效令牌!";
			return createDtoResponse(Status::CODE_200, result);
		}

		// 获取登录参数
		auto oldPassword = vo->oldPassword;
		auto newPassword = vo->newPassword;
		if (oldPassword.getValue("") != SystemConfig::get_mutable_instance().GetBoxConf().GetUser().GetPassword())
		{
			result->description = "原密码错误!";
			return createDtoResponse(Status::CODE_200, result);
		}

		// 更新用户密码
		ConfigService configService;
		if (configService.UpdateAdmin(SystemConfig::get_mutable_instance().GetBoxConf().GetUser())){
			SystemConfig::get_mutable_instance().GetBoxConf().GetUser().SetPassword(newPassword);
		}

		// 返回登录结果
		result->error = 0;
		result->description = "success";
		return createDtoResponse(Status::CODE_200, result);
	}
};

#include OATPP_CODEGEN_END(ApiController)